/**
 * @Time: 2018/11/22 15:28
 * @Author: wangmin
 * @File: func
 * @Software: GoLand
 */
package object

import (
	"errors"
	"time"
	"strconv"
	"open_manjing/microsys/encryption"
	"github.com/astaxie/beego"
	"net/url"
	"strings"
)

//授权
func auth(authType int8, expiryTime int64, id int) (error, string) {
	authString := strconv.Itoa(int(authType)) + "&"
	switch authType {
	case 1:
		if expiryTime < time.Now().Unix() {
			return errors.New("临时授权过期时间不能设定在过去的时间"), ""
		}
		authString += strconv.FormatInt(expiryTime, 10)
	case 2:
		if id == 0 {
			return errors.New("对象授权时对象id不能为空"), ""
		}
		authString += strconv.Itoa(id)
	default:
		return errors.New("授权类型非法"), ""
	}
	key := []byte(beego.AppConfig.String("cluster.key"))
	iv := []byte(beego.AppConfig.String("cluster.iv"))
	authString, err := encryption.AesEncrypt(authString, key, iv)
	return err, url.QueryEscape(authString)
}

//临时授权
func TmpAuth(expiryTime int64) (error, string) {
	return auth(1, expiryTime, 0)
}

//对象永久授权
func ForeverAuth(id int) (error, string) {
	return auth(1, 0, id)
}

//解析授权码
func parseAuthCode(authCode string) (err error, expiryTime int64, id int) {
	if authCode == "" {
		err = errors.New("授权码不能为空")
		return
	}
	authCode, e := url.QueryUnescape(authCode)
	if e != nil {
		err = errors.New("授权码转码失败")
		return
	}
	key := []byte(beego.AppConfig.String("cluster.key"))
	iv := []byte(beego.AppConfig.String("cluster.iv"))
	authCodeB, e := encryption.AesDecrypt(authCode, key, iv)
	if e != nil {
		err = errors.New("授权码解析失败")
		return
	}
	authCodeA := strings.Split(string(authCodeB), "&")
	if len(authCodeA) != 2 {
		err = errors.New("授权码错误")
		return
	}
	authType, e := strconv.Atoi(authCodeA[1])
	if e != nil {
		err = errors.New("授权码错误无法获取类型")
		return
	}
	switch authType {
	case 1:
		et, e := strconv.ParseInt(authCodeA[2], 10, 64)
		if e != nil {
			err = errors.New("授权码错误无法过期时间")
			return
		}
		expiryTime = et
		return
	case 2:
		aId, e := strconv.Atoi(authCodeA[2])
		if e != nil {
			err = errors.New("授权码错误无法过期时间")
			return
		}
		id = aId
		return
	default:
		err = errors.New("授权码错误类型错误")
		return
	}
}

//验证临时授权
func CheckTmpAuth(authCode string) error {
	err, expiryTime, _ := parseAuthCode(authCode)
	if err != nil {
		return err
	}
	if expiryTime < time.Now().Unix() {
		return errors.New("授权码过期")
	}
	return nil
}

//验证对象授权
func CheckObjectAuth(authCode string, id int) error {
	err, _, aId := parseAuthCode(authCode)
	if err != nil {
		return err
	}
	if id != aId {
		return errors.New("授权码错误")
	}
	return nil
}
